package band.wukong.practice.javase.core.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * V2：支持多个客户端，多线程
 * User: Johnson
 * Date: 2012-8-24 15:55:22
 * To change this template use File | Settings | File Templates.
 */
public class ServerV3 extends Thread {
    private Socket client;

    public ServerV3(Socket client) {
        this.client = client;
    }

    public void run() {
        try {
            BufferedReader in =
                    new BufferedReader(
                            new InputStreamReader(client.getInputStream()));

            //4.获得并包装输入
            PrintWriter out = new PrintWriter(client.getOutputStream());

            //5.开搞！
            while (true) {
                String str = in.readLine();
                System.out.println(str);
                out.println("[Server]has receive....");
                out.flush();
                if (str.equals("end"))
                    break;
            }

            //6.打完收工
            client.close();
        } catch (IOException e) {
        } finally {
        }
    }


    public static void main(String[] args) throws IOException {
        //1.创建ServerSocket
        ServerSocket server = new ServerSocket(5678);

        while (true) {
            //2.开始监听，并获得对应Socket client
            ServerV3  v3 = new ServerV3(server.accept());
            v3.start();
        }
    }
}
